package com.android.luhnchecking;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.android.luhnchecking.adapter.AccountAdapter;
import com.android.luhnchecking.db.AccountDao;

public class MainActivity extends Activity {
	public static final String TAG = "ACCOUNT";
	private EditText accountNumberEt;
	private TextView validationTv;
	private ListView accountLv;
	private AccountAdapter adapter;
	private List<LuhnNumber> numbers;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		accountNumberEt = (EditText) findViewById(R.id.et_input_number);
		validationTv = (TextView) findViewById(R.id.tv_validation_message);
		accountLv = (ListView) findViewById(R.id.lv_accounts);
		init();
	}

	private void init() {
		numbers = new ArrayList<LuhnNumber>();
		adapter = new AccountAdapter(this, numbers);
		accountLv.setAdapter(adapter);
		// add dump data for header
		adapter.add(new LuhnNumber());

		accountNumberEt.setText("79927398713");

		AccountDao accountDao = new AccountDao(this);
		showAccount(accountDao);
	}

	public void onClick(View view) {
		String number = accountNumberEt.getEditableText().toString();
		LuhnNumber luhnNumber = new LuhnNumber();
		luhnNumber.setValue(number);

		boolean is11DigitNumber = AccountUtils.isValidNumber(luhnNumber);
		if (!is11DigitNumber) {
			validationTv.setText("The account number " + number
					+ " must be an 11 digit number.");
		} else {
			boolean pass = AccountUtils.check(luhnNumber);
			luhnNumber.setPassed(pass);
			luhnNumber.setTimeStamp(System.currentTimeMillis());
			AccountDao accountDao = new AccountDao(this);
			accountDao.insert(luhnNumber);

			showAccount(accountDao);

			validationTv.setText("");
		}
	}

	private void showAccount(AccountDao accountDao) {
		List<LuhnNumber> list = accountDao.getAll();
		adapter.clear();
		for (LuhnNumber luhnNumber2 : list) {
			adapter.add(luhnNumber2);
		}
	}
}
